﻿using System.Windows.Data;
using System.Windows.Input;
using FamilyBook.UI.WPF.Interaction;
using Microsoft.Practices.Prism.Commands;

namespace FamilyBook.UI.WPF.ViewModels
{
    public abstract class BaseListViewModel<TDetailsViewModel> where TDetailsViewModel : IViewModel
    {
        protected BaseListViewModel()
        {
            AddNewCommand = new DelegateCommand(AddNew, CanAddNew);
            ShowDetailsCommand = new DelegateCommand(ShowDetails, CanShowDetails);

            ShowDetailsRequest = new DetailsInteractionRequest<TDetailsViewModel>();
        }

        public ICommand AddNewCommand { get; protected set; }
        public ICommand ShowDetailsCommand { get; private set; }

        public DetailsInteractionRequest<TDetailsViewModel> ShowDetailsRequest { get; set; }

        public ListCollectionView ListModel { get; protected set; }

        protected abstract TDetailsViewModel CreateDetailsViewModel();

        protected virtual void ShowDetails()
        {
            var detailsModel = (TDetailsViewModel)ListModel.CurrentItem;
            ShowDetailsRequest.Raise(detailsModel, ShowDetailsConfirmed, ShowDetailsCanceled);
        }
        protected virtual bool CanShowDetails()
        {
            return true;
        }
        protected virtual void ShowDetailsConfirmed(TDetailsViewModel detailsModel)
        {
            ListModel.Refresh();
        }
        protected virtual void ShowDetailsCanceled(TDetailsViewModel detailsModel)
        {
        }

        protected virtual void AddNew()
        {
            TDetailsViewModel detailsModel = CreateDetailsViewModel();
            ShowDetailsRequest.Raise(detailsModel, AddNewConfirmed, AddNewCanceled);
        }
        protected virtual bool CanAddNew()
        {
            return true;
        }
        protected virtual void AddNewConfirmed(TDetailsViewModel detailsModel)
        {
            ListModel.AddNewItem(detailsModel);
        }
        protected virtual void AddNewCanceled(TDetailsViewModel detailsModel)
        {
        }
    }
}
